<?php
class Flashgame_Widget_ListingGamesController extends Engine_Content_Widget_Abstract
{
  public function indexAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $subject = Engine_Api::_()->getItem('flashgame_param', 1);
    $values = null;
    if($viewer->getIdentity() )
        $values['show']= $subject->show; 
    $values['category']= $subject->category; 
    $values['page']= $subject->page; 
    $values['tag']= $subject->tag;
    $values['orderby']= $subject->orderby; 
    $values['search']= $subject->search;
     if($_POST)
      {
          $values['orderby']= $_POST['orderby'];
          $values['search']= $_POST['search'];
          $values['tag']= $_POST['tag'];
          $values['category']=  $_POST['category'];
          if($viewer->getIdentity() )
                $values['show'] =  $_POST['show'];
      } 
    $form = new Flashgame_Form_Search();
    $customFieldValues = array_intersect_key($values, $form->getFieldElements());
       // Do the show thingy
        if( @$values['show'] == 2 )
        {
            // Get an array of friend ids to pass to getflashgamesPaginator
            $table = Engine_Api::_()->getItemTable('user');
            $select = $viewer->membership()->getMembersSelect('user_id');
            $friends = $table->fetchAll($select);
            // Get stuff
            $ids = array();
            foreach( $friends as $friend )
            {
                $ids[] = $friend->user_id;
            }
            //unset($values['show']);
            if (sizeof($ids) < 1)
                $values['users'] = array('0'=>0);
            else
                $values['users'] = $ids; 
        }

        // check to see if request is for specific user's listings
        $user_id = $this->_getParam('user');
        if ($user_id)
        {
            $values['user_id'] = $user_id;
        }

        //die($this->_getParam('page',1)."");
        $this->view->assign($values);

        // items needed to show what is being filtered in browse page
        if (!empty($values['tag']))
            $this->view->tag_text = Engine_Api::_()->getItem('core_tag', $values['tag'])->text;
        $view = $this->view;
        $view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
        $values["closed"] = 0;

        $paginator = Engine_Api::_()->flashgame()->getFlashgamesPaginator($values, $customFieldValues);
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('flashgame.page', 10);
        $paginator->setItemCountPerPage($items_count);
        $currentpage = isset($_POST["page"])?$_POST["page"]:1;
        $this->view->paginator = $paginator->setCurrentPageNumber($currentpage);

        if( !empty($values['category']) )
            $this->view->categoryObject = Engine_Api::_()->flashgame()->getCategory($values['category']);
  }
}
